package ThreadPool.lagou.concurrent.demo03;

/**
 * @param
 * @author oyz
 * @version 1.0.4
 * @description: 生产者消费者队列
 * @date 2022/5/24 20:38
 */
public class MyQueue2 extends MyQueue{

    private String [] data = new String[10];
    // 生产数据的坐标
    private int putIndex = 0;
    // 消费数据的坐标
    private int getIndex = 0;
    // 记录数组的长度
    private int size = 0;

    /**
     * 生产方法
     * @param element
     * @throws InterruptedException
     */
    @Override
    public synchronized void put(String element) throws InterruptedException {
        if(size == data.length){
            wait();
            put(element);
        }else{
            put0(element);
        }


    }

    private void put0(String element){
        data[putIndex] = element;
        ++size;
        ++putIndex;
        notify();
        if(putIndex == data.length){
            putIndex = 0;
        }
    }

    /**
     * 消费方法
     */
    @Override
    public synchronized String get() throws InterruptedException {
        if(size == 0){
            wait();
            // 利用迭代重新出去抢锁
            return get();
        }else{
            return get0();
        }
    }

    private String get0(){
        String object = data[getIndex];
        ++getIndex;
        size--;
        notify();
        if(getIndex == data.length){
            getIndex = 0;
        }
        return object;
    }


}
